package com.ysx.search.consumer;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysx.behaviour.feign.ApBehaviorEntryFeign;
import com.ysx.behaviour.pojo.ApBehaviorEntry;
import com.ysx.common.constants.BusinessConstants;
import com.ysx.search.mapper.ApUserSearchMapper;
import com.ysx.search.pojo.ApUserSearch;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Component
public class SearchUserBehaviourConsumer {

    @Autowired
    private ApUserSearchMapper apUserSearchMapper;

    @Autowired
    private ApBehaviorEntryFeign apBehaviorEntryFeign;


    //接收消息
    @KafkaListener(topics = BusinessConstants.MqConstants.SEARCH_BEHAVIOR_TOPIC)
    public void recevieMessageSearch(ConsumerRecord<String, String> record) {
        String value = record.value();//消息本身 就是JSON
        Map<String,String> map = JSON.parseObject(value, Map.class);

        //记录下数据到数据库中

        ApUserSearch entity = new ApUserSearch();
        entity.setCreatedTime(LocalDateTime.now());
        entity.setKeyword(map.get("keywords"));
        entity.setStatus(1);

        String userId = map.get("userId");
        String type = map.get("type");
        ApBehaviorEntry entry = apBehaviorEntryFeign.findByUserIdOrEquipmentId(Integer.valueOf(userId),Integer.valueOf(type));
        if(entity==null){
            //日志进行error记录下来
            return;
        }
        entity.setEntryId(entry.getId());
        QueryWrapper<ApUserSearch> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("entry_id",entry.getId());
        queryWrapper.eq("keyword",map.get("keywords"));
        queryWrapper.eq("status",1);

        List<ApUserSearch> apUserSearches = apUserSearchMapper.selectList(queryWrapper);
        if(apUserSearches!=null && apUserSearches.size()>0){
            //存在记录
            return;
        }

        apUserSearchMapper.insert(entity);
    }
}